#encoding 'utf-8'
load 'rds_api.rb'
@rds = @rds_tt

# eb_spreader_daily_report的人工操作

#2023-07-22 用于修补和升级tutem_mall.eb_spreader_daily_report表
def update_user_lists_in_reports

    # Fetch all records from `tutem_mall.eb_spreader_daily_report`
    results = @rds.query("SELECT * FROM tutem_mall.eb_spreader_daily_report")

    results.each do |result|
        # Parse string arrays into Ruby arrays
        recruited_list = JSON.parse(result['recruited_list'])
        first_order_list = JSON.parse(result['first_order_list'])
        qpo_list = JSON.parse(result['qpo_list'])

        mta_recruited_list, npo_user_list, qpo_user_list = [], [], []

        # Fetch mta_recruited_list
        unless recruited_list.empty?
            mta_recruited_list = @rds.query(
                "SELECT uid FROM tutem_mall.eb_user WHERE uid IN (#{recruited_list.join(',')}) AND login_type='mta'"
            ).map { |res| res['uid'] }
        end
    
        # Fetch npo_user_list and qpo_user_list
        unless first_order_list.empty?
            npo_user_list = @rds.query(
                "SELECT uid FROM tutem_mall.eb_store_order WHERE id IN (#{first_order_list.join(',')})"
            ).map { |res| res['uid'] }
        end

        unless qpo_list.empty?
            qpo_user_list = @rds.query(
                "SELECT uid FROM tutem_mall.eb_store_order WHERE id IN (#{qpo_list.join(',')})"
            ).map { |res| res['uid'] }
        end

        # Update the current record with the new lists
        sql = 
            "UPDATE tutem_mall.eb_spreader_daily_report SET mta_recruited_list='#{mta_recruited_list.to_json}', mta_recruited_count = #{mta_recruited_list.size}, \
            npo_user_list='#{npo_user_list.to_json}', qpo_user_list='#{qpo_user_list.to_json}' \
            WHERE date='#{result['date']}' AND spreader_uid=#{result['spreader_uid']}"

        @rds.query(sql) #if ( mta_recruited_list.size + npo_user_list.size + qpo_user_list.size > 0 )

    end

end
#update_user_lists_in_reports
